<template>
  <el-dialog width="50%" title="调用的API" :close-on-click-modal="false">
    <el-form ref="formRef" :model="dynamicValidateForm" style="width: 100%">
      <el-form-item
        style="width: 100%"
        v-for="(domain, index) in dynamicValidateForm.domains"
        :key="domain.key"
        size="large"
        :label="'API' + (index + 1) + ':'"
        :prop="'domains.' + index + '.title'"
        :rules="[
          {
            required: true,
            message: 'API不能为空',
            trigger: 'blur',
          },
          {
            required: true,
            message: 'API不能为空',
            trigger: 'change',
          },
        ]"
      >
        <!--        <el-row style="width: 100%">-->
        <div style="width: 100%">
          <el-row>
            <el-col :span="5">
              <div style="width: 100%">
                <el-autocomplete
                  v-model="domain.title"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入API"
                  clearable
                  @input="changeInput(domain)"
                  @select="handleSelect(domain)"
                /></div
            ></el-col>
            <el-col :span="15">
              <div style="width: 100%">
                <el-input v-model="domain.value" readonly></el-input></div
            ></el-col>
            <el-col :span="2">
              <div style="width: 100%">
                <el-button class="mt-2" @click.prevent="removeDomain(domain)"
                  >删除
                </el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">确认</el-button>
        <el-button @click="addDomain">新增</el-button>
        <el-button @click="close()">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import DataOption from "@/components/table/simple/DataOption";
import api from "@/utils";

export interface domain {
  key?: number;
  apiId?: number;
  title?: string; // api的名称
  value?: string; // api的值
}
export interface dataList {
  menuId: number;
  backendApiId: number;
  createUser: string;
  createGmt: Date;
}

export interface apiProps {
  apiList: Array<domain>; // 当前菜单具有的api
  currentMenuId: number; // 当前菜单的id
}

const props = withDefaults(defineProps<apiProps>(), {
  apiList: () => {
    return [{ key: Date.now(), title: "", value: "" } as domain];
  },
});
const emits = defineEmits<{
  (e: "close"): void;
}>();
const formRef = ref();
const dynamicValidateForm = reactive({
  domains: [{ key: Date.now(), title: "" } as domain],
});
// 输入框搜索时下方展示的列表
const restaurants = ref([] as Array<Record<string, string | number>>);

const { data, getRecord } = DataOption();
// 获取数据，给列表赋值
const getApiRecord = () => {
  getRecord("/basic-request/backend-api/search").then(() => {
    for (let i = 0; i < data.value.length; i++) {
      const temp = data.value[i] as Record<string, unknown>;
      restaurants.value.push({
        value: temp.fullName as string,
        title: temp.apiPath as string,
        apiId: temp.id as number,
      });
    }
  });
};
getApiRecord();
// 动态添加一条api
const addDomain = () => {
  dynamicValidateForm.domains.push({
    key: Date.now(),
    apiId: -2,
    title: "",
    value: "",
  });
};
const querySearch = (
  queryString: string,
  cb: (data: Array<unknown>) => void
) => {
  const results = queryString
    ? restaurants.value.filter((item) =>
        createFilter(item as Record<string, string>, queryString)
      )
    : restaurants.value;
  cb(results);
};

const createFilter = (item: Record<string, string>, queryString: string) => {
  return item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
};
// 当输入框选择一条数据时，完善这条数据的其他属性，被选择数据apiID(提交后台数据使用),fullName(展示使用)
const handleSelect = (domain: domain) => {
  restaurants.value.forEach((item) => {
    if (item.value == domain.title) {
      domain.value = item.title as string;
      domain.apiId = item.apiId as number;
    }
  });
  formRef.value.validate(); // 手动表单校验一下，不然会有校验样式出错的问题
};
// 当输入框数据为空时，给当前输入框动态添加的属性也清空(只需清空fullName即可)
const changeInput = (domain: domain) => {
  if (domain.title == "") {
    domain.value = "";
  }
};
const close = () => {
  emits("close");
};
// 移除一条数据
const removeDomain = (item: domain) => {
  const index = dynamicValidateForm.domains.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1);
  }
};
// 提交数据
const submitForm = () => {
  if (!formRef.value) return;
  formRef.value
    .validate()
    .then(() => {
      // 遍历生成后台需要的数据格式
      let menuData = [] as Array<dataList>;
      dynamicValidateForm.domains.forEach((item) => {
        menuData.push({
          menuId: props.currentMenuId,
          backendApiId: item.apiId as number,
          createUser: sessionStorage.getItem("userName") as string,
          createGmt: new Date(),
        });
      });
      api.http.postJson("/system/setMenuBackendApiRelation", menuData);
    })
    .catch(() => {
      console.log("验证失败");
    });
};
// 清空校验规则
const clearValidateData = () => {
  if (formRef.value) formRef.value.clearValidate();
};
// 监听事件 选择某一菜单时，初始化这一菜单具有那些api
watch(
  () => props.apiList,
  () => {
    console.log(props.apiList);
    dynamicValidateForm.domains = [];
    props.apiList.forEach((api: any) => {
      dynamicValidateForm.domains.push({
        key: Date.now(),
        apiId: api.id,
        title: api.fullName,
        value: api.apiPath,
      });
    });
  },
  { immediate: true }
);
// 抛出事件 每次打开弹窗时清空校验内容
defineExpose({ clearValidateData });
</script>
<style scoped></style>
